package com.example.cinema;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.cinema.adapter.CarouselAdapter;
import com.example.cinema.adapter.RecyclerTypeAdapter;
import com.example.cinema.bindingdata.Advert;
import com.example.cinema.bindingdata.CarouseData;
import com.example.cinema.bindingdata.LiveTableData;
import com.example.cinema.bindingdata.LiveTypeData;
import com.example.cinema.bindingdata.MovieData;
import com.example.cinema.bindingdata.NoticeGGData;
import com.example.cinema.bindingdata.TypeData;
import com.example.cinema.bindingdata.TypeFragmentData;
import com.example.cinema.bindingdata.VideoData;
import com.example.cinema.database.DataBaseMethod;
import com.example.cinema.databinding.FragmentBlank0Binding;
import com.example.cinema.fragment.AdverItemFragment;
import com.example.cinema.fragment.TypeVieoFragment;
import com.example.cinema.request.BlanFragmentRequest;
import com.example.cinema.request.RequestData;
import com.example.cinema.testdara.TestData;
import com.example.cinema.toolclass.SvgaUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BlankFragment0#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment0 extends Fragment {


    @Override
    public void onResume() {
        super.onResume();
        SvgaStart();
        if(timer!=null)
        {
            TimerMethods();
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        if(timer!=null)
        {
            timer.cancel();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(timer!=null)
        {
            timer.cancel();
        }
    }

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public BlankFragment0() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment0.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment0 newInstance(String param1, String param2) {
        BlankFragment0 fragment = new BlankFragment0();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    private static FragmentBlank0Binding FBB;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (!isinit) {
            FBB = DataBindingUtil.inflate(inflater, R.layout.fragment_blank0, container, false);


        }
        if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
        {
            View view = container.getRootView();
            view.setSystemUiVisibility(View.GONE);
        }else if(Build.VERSION.SDK_INT>=19){
            View view = container.getRootView();
            int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(UIOP);
        }

        return FBB.getRoot();
    }


    private UserAttribute attribute;
    private static boolean isinit = false;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.i("KKKE", isinit + "");
        attribute = (UserAttribute) getActivity().getApplication();
        if (!isinit) {

            init();
            inits();
            inittypevideoa();
        }
    }


    private RecyclerTypeAdapter readapter;
    private List<LiveTypeData> LiveList = new ArrayList<>();

    private void init() {
        FBB.sharerecycler.setLayoutManager(new GridLayoutManager(getContext(),4));
        readapter = new RecyclerTypeAdapter(getContext(), LiveList, R.layout.type_item);
        FBB.sharerecycler.setAdapter(readapter);

        readapter.setOnItemClickListener(new RecyclerTypeAdapter.setOnItemClick() {
            @Override
            public void onitemClick(View view, Object object) {
                Intent intent = new Intent();
                if (attribute.getUID() == null || attribute.getToken() == null) {
                    intent.setAction("sign");
                } else {
                    intent.putExtra("postion",(int)object);
                    intent.setAction("livelist");
                }
                startActivity(intent);
            }
        });
        GetLiveType();
    }

    private List<CarouseData> Lundata = new ArrayList<>();
    private CarouselAdapter Lunadapter;
    private Map<String, String> noticemap;

    private void inits() {

        //轮播数据
        DataBaseMethod poster = new DataBaseMethod(getContext(), "poster");
        Lundata = poster.GetLunBo();
        Log.i("QQQQQ", Lundata.size() + "");
        if (Lundata.size() > 0) {
            Log.i("QQQQQ", Lundata.size() + "");
            Log.i("QQQQQ", Lundata.get(0).imgurl);
            Lunadapter = new CarouselAdapter(Lundata, getContext());
            FBB.viewpage.setAdapter(Lunadapter);
            TimerMethods();
        }

        //公告
        DataBaseMethod notice = new DataBaseMethod(getContext(), "notice");
        Map<String, String> noticedata = notice.GetNotice();
        if (noticedata.size() > 0) {
            Log.i("KKK", "非空");
            noticemap = noticedata;
            initNotice();
        }

        //轮播点击
        if(Lunadapter==null)
        {
            return;
        }
        Lunadapter.setOnPageItemClickListener(new CarouselAdapter.OnPageItemClickListener() {
            @Override
            public void itemClick(CarouseData cdata, int positon) {
                Log.i("HHHSD",cdata.news+"");
                if(cdata.type==0)
                {
                    if(cdata.news!=null)
                    {
                        Intent intent = new Intent();
                        intent.setAction(cdata.news);
                        startActivity(intent);
                    }

                    return;
                }
                if(cdata.type==1)
                {
                    Uri uri =  Uri.parse(cdata.address);
                    Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                    startActivity(intent);
                }
            }
        });
    }

    private void  GetLiveType()
    {
        new Thread()
        {
            @Override
            public void run() {
                //直播分类
                RequestData requestData = new RequestData(getContext());
                List<LiveTypeData>  data = requestData.ReqLiveData();
                Log.i("SASASS",   data.get(0).typeicon.get());
                LiveList.addAll(data);
                Message message = new Message();
                message.obj = data;
                message.what= 1005;
                handler.sendMessage(message);
            }
        }.start();
    }


    private SvgaUtils svgaUtils;

    private void SvgaStart() {
        svgaUtils = new SvgaUtils(getContext(), FBB.svglive);
        svgaUtils.init();
        svgaUtils.startAnimator("remen");
    }


    //动态添加模块
    private List<ImageView> listimg = new ArrayList<>();
    private LinearLayout.LayoutParams layoutParams;
    private List<Advert> imgadvert;
    private void inittypevideoa() {

        layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.height = 200;

        DataBaseMethod baseMethods = new DataBaseMethod(getContext(), "adverdatas");
        imgadvert = baseMethods.GetFramAdv();
        Log.i("HHHDD",imgadvert.size()+"数量");
        DataBaseMethod baseMethod = new DataBaseMethod(getContext(), "videotype");
        List<MovieData> typadata = baseMethod.GetTypeData();

        for (int i = 0; i < typadata.size(); i++) {
            if(typadata.get(i).typetags.equals("1024"))
            {
                continue;
            }
            MovieData movieData = typadata.get(i);
            GetVideoFrame(movieData.typetags, movieData.typename);
        }
    }

    //获取数据
    private void GetVideoFrame(String tid, String title) {
        new Thread() {
            @Override
            public void run() {
                RequestData requestData = new RequestData(getContext());
                List<VideoData> vdata = requestData.GetCai(tid);
                if (vdata.size() < 1) {
                    return;
                }
                Log.i("PPP", vdata.size() + "");
                Log.i("PPP", vdata.get(0).videosid.get());
                Log.i("PPP", vdata.get(0).videopart.get());
                TypeFragmentData fragmentData = new TypeFragmentData();
                fragmentData.typename.set(title);
                Log.i("QWQWQW",title);
                fragmentData.typedata.set(vdata);
                fragmentData.typetag.set(tid);

                Log.i("TTTTS",vdata.get(0).videotime.get());

                Message message = new Message();
                message.what = 1003;
                message.obj = fragmentData;
                handler.sendMessage(message);
            }
        }.start();
    }

    //公告
    private AlertDialog NoticeDialog;
    private void initNotice() {
        int width = getResources().getDisplayMetrics().widthPixels;
        NoticeGGData data = new NoticeGGData();
        data.title.set(noticemap.get("title"));
        data.btntext.set("知道了");
        data.centext.set(noticemap.get("texts"));
        ViewDataBinding dataBinding = DataBindingUtil.inflate(LayoutInflater.from(getActivity()), R.layout.dialog_item_notice, null, false);
        dataBinding.setVariable(BR.niticedata, data);
        NoticeDialog = new AlertDialog.Builder(getActivity()).setView(dataBinding.getRoot()).create();
        NoticeDialog.setCancelable(false);
        NoticeDialog.show();
        NoticeDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {

                if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
                {
                    View view = getView();
                    view.setSystemUiVisibility(View.GONE);
                }else if(Build.VERSION.SDK_INT>=19){
                    View view = getView();
                    int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
                    view.setSystemUiVisibility(UIOP);
                }
            }
        });

        Window window = NoticeDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setBackgroundColor(Color.parseColor("#00000000"));
        window.setWindowAnimations(R.style.dialoganim);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = width/6*5;
        window.setAttributes(params);

        View closeview = dataBinding.getRoot().findViewById(R.id.closebtn);
        closeview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {



                NoticeDialog.cancel();


            }
        });
        isinit = true;

        if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
        {
            View view = closeview.getRootView();
            view.setSystemUiVisibility(View.GONE);
        }else if(Build.VERSION.SDK_INT>=19){
            View view = closeview.getRootView();
            int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(UIOP);
        }
    }

    Handler handler = new Handler(Looper.getMainLooper()) {
        int p = 0;
        int w = 1;
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1003) {

                Log.i("eeeee", "------------");
                TypeFragmentData fragmentData = (TypeFragmentData) msg.obj;
                Log.i("eeeee", fragmentData.typedata.get().size() + "");
                TypeVieoFragment fragment = new TypeVieoFragment();
                Log.i("eeeee", "------------"+fragmentData.typetag.get());
                Log.i("eeeee", "------------"+fragmentData.typename.get());
                fragment.setDatas(fragmentData);
                FragmentManager manager = getChildFragmentManager();
                FragmentTransaction Ft = manager.beginTransaction();
                Ft.add(R.id.linear, fragment, "as"+w);
                Ft.commitAllowingStateLoss();

                if(imgadvert.size()>0) {
                    AdverItemFragment adveritem = new AdverItemFragment();
                    adveritem.setData(imgadvert.get(0));
                    FragmentManager manager1 = getChildFragmentManager();
                    FragmentTransaction Ft1 = manager1.beginTransaction();
                    Ft1.add(R.id.linear, adveritem, "aa");
                    Ft1.commitAllowingStateLoss();
                }
                w++;
                return;
            }
            if(msg.what == 1004) {
                int i = (int) msg.obj;
                FBB.viewpage.setCurrentItem(i);
            }
            if(msg.what == 1005){
                readapter.notifyDataSetChanged();
//                new GridViewHeight(FBB.sharerecycler,4);
            }
        }
    };


    private Timer timer;
    private TimerTask timerTask;
    private void TimerMethods()
    {
        int size = Lundata.size();

        timer = new Timer();
        timerTask = new TimerTask() {
            int poss = 0;
            @Override
            public void run() {
                if(poss<size)
                {
                    Message message = new Message();
                    message.what = 1004;
                    message.obj = poss;
                    handler.sendMessage(message);
                    poss++;
                }else {
                    poss = 0;
                }
            }
        };
        timer.schedule(timerTask,1000,5000);
    }

}